using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{
	
	public int Health;
	public bool Invencible;
	
	public AudioClip PlayerCollision;
	
	public Vector2 Velocity;
	public Rect Bounds;
	public float BaseVelocity;
	public float Displacement;
	public Vector2 Offset;
	
	void Update()
	{
		Vector2 adjustment = new Vector2(
			Input.GetAxis("Horizontal") * Velocity.x,
			Input.GetAxis("Vertical") * Velocity.y
		) * Time.smoothDeltaTime;
		
		if (adjustment.x != 0.0f)
			Offset.x = Mathf.Clamp(
				Offset.x + adjustment.x,
				Bounds.xMin,
				Bounds.xMax
			);
		
		if (adjustment.y != 0.0f)
			Offset.y = Mathf.Clamp(
				Offset.y + adjustment.y,
				Bounds.yMin,
				Bounds.yMax
			);
		
		Vector3 position = transform.position;
		
		position.x = Offset.x;
		position.z = Offset.y;
		
		Displacement += (BaseVelocity + (Offset.y - Bounds.yMin) / Bounds.yMax * Velocity.y) * Time.smoothDeltaTime;
		
		position.z += Displacement;
		
		transform.position = position;
	}
		
	void OnCollisionEnter(Collision collision)
	{
		PushAway(collision);
	}
	
	void OnCollisionStay(Collision collision)
	{
		PushAway(collision);
	}
	
	void PushAway(Collision collision)
	{
		float highest = collision.contacts[0].point.x;
		float lowest = collision.contacts[0].point.x;
		for (int i = 1; i < collision.contacts.Length; i++)
		{
			if (Mathf.Abs(highest) < Mathf.Abs(collision.contacts[i].point.x))
				highest = collision.contacts[i].point.x;
			if (Mathf.Abs(lowest) > Mathf.Abs(collision.contacts[i].point.x))
				lowest = collision.contacts[i].point.x;
		}
		
		if (lowest > transform.position.x)
			Offset.x = lowest - (lowest - transform.position.x);
		else
			Offset.x = lowest + (transform.position.x - lowest);
		
		rigidbody.velocity = Vector3.zero;
	}
	
	void OnTriggerEnter(Collider collider)
	{
		switch (collider.name)
		{
		case "Enemy":
			if (!Invencible)
			{
				audio.PlayOneShot(PlayerCollision);
				Health--;
				if (Health <= 0)
					Application.LoadLevel("05_GameOver");
			}
			break;
		}
	}
	
}